package com.tuyenmonkey.mkloader.type;

import com.tuyenmonkey.mkloader.model.Line;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Point;

import java.math.BigDecimal;

public class LineSpinner extends LoaderView{
  private Line[] lines;
  private int numberOfLine;

  public LineSpinner() {
    numberOfLine = 8;
  }

  @Override public void initializeObjects() {
    int size = Math.min(width, height);
    float lineWidth = size / 10f;
    lines = new Line[numberOfLine];

    for (int i = 0; i < numberOfLine; i++) {
      lines[i] = new Line();
      lines[i].setColor(color);
      lines[i].setAlpha(126);
      lines[i].setWidth(lineWidth);
      lines[i].setPoint1(new Point(center.getPointX(), new BigDecimal(center.getPointY()).subtract(new BigDecimal(size).divide(new BigDecimal(2))).add(new BigDecimal(lineWidth)).floatValue()));

      lines[i].setPoint2(new Point(center.getPointX(), new BigDecimal(lines[i].getPoint1().getPointY()).add(new BigDecimal(2).multiply(new BigDecimal(lineWidth))).floatValue()));

    }
  }

  @Override public void setUpAnimation() {
    for (int i = 0; i < numberOfLine; i++) {
      final int index = i;
      AnimatorValue fadeAnimator = new AnimatorValue();
      fadeAnimator.setLoopedCount(AnimatorValue.INFINITE);
      fadeAnimator.setDuration(1000);
      fadeAnimator.setDelay(index * 120);
      fadeAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
        @Override
        public void onUpdate(AnimatorValue animatorValue, float v) {
          lines[index].setAlpha(v);
          if (invalidateListener != null) {
            invalidateListener.reDraw();
          }
        }
      });
      fadeAnimator.start();
    }
  }


  @Override public void draw(Canvas canvas) {
    for (int i = 0; i < numberOfLine; i++) {
      canvas.save();
      canvas.rotate(45 * i, center.getPointX(), center.getPointY());
      lines[i].draw(canvas);
      canvas.restore();
    }
  }

}
